from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from typing import List, Dict

from models.sensor_data import SensorData
from algorithms.feature_extraction import extract_features
from algorithms.classification import classify_odor

# 创建FastAPI应用
app = FastAPI(
    title="电子鼻数据分析系统",
    description="提供电子鼻传感器数据处理和气味分类的API服务",
    version="1.0.0"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源，生产环境中应该限制
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/health")
async def health_check():
    """健康检查端点"""
    return {"status": "healthy"}

@app.post("/analyze")
async def analyze_data(data: SensorData):
    """
    分析传感器数据并执行气味分类
    
    接收传感器读数，执行特征提取和气味分类，返回分析结果
    """
    try:
        # 验证数据
        if not data.sensor_readings or len(data.sensor_readings) == 0:
            raise HTTPException(status_code=400, detail="传感器数据不能为空")
            
        # 提取特征
        features = extract_features(data.sensor_readings)
        
        # 执行分类
        classification_result = classify_odor(features)
        
        # 返回结果
        return {
            "features": features.tolist(),
            "classification": classification_result,
            "metadata": data.metadata
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"分析过程中发生错误: {str(e)}")

@app.get("/")
async def root():
    """API根端点，提供基本信息"""
    return {
        "name": "电子鼻数据分析系统API",
        "version": "1.0.0",
        "docs_url": "/docs",
        "redoc_url": "/redoc"
    } 